package edu.scau.sku.service;

import edu.scau.core.Enum.SkuRecordType;
import edu.scau.core.exection.BusinessProcessException;
import edu.scau.core.util.ServletUtils;
import edu.scau.sku.domain.Sku;
import edu.scau.sku.mapper.SkuColorSizeMapper;
import edu.scau.sku.mapper.SkuMapper;
import edu.scau.sku.service.SkuService;
import edu.scau.sku.vo.SkuVo;
import edu.scau.system.domain.LoginUser;
import edu.scau.system.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.TransactionAnnotationParser;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class SkuServiceImpl implements SkuService {
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SkuColorSizeMapper skuColorSizeMapper;
    @Autowired
    private SkuRecordService skuRecordService;
    @Override
    public List<SkuVo> listAll() {
        return skuMapper.listAll();
    }

    @Override
    public SkuVo findSkuByCode(String skuCode) {
        return skuMapper.findSkuByCode(skuCode);
    }

    @Override
    public List<SkuVo> listByPage(SkuVo skuVo) {
       return skuMapper.listByPage(skuVo);
    }

    @Override
    public int updateSku(SkuVo skuVo) {
        if(skuVo.getSkuCode().isEmpty()){
            throw new IllegalArgumentException("库存编号不能为空！");
        }
        if(! isExisted(skuVo.getSkuCode())){
            throw new IllegalArgumentException("不存在该库存！");
        }
        LoginUser loginUser=tokenService.getLoginUser(ServletUtils.getRequest());
        String updateBy=loginUser.getUsername();
        Date updateTime = new Date();
        Sku sku = new Sku(skuVo);
        sku.setUpdateBy(updateBy);
        sku.setUpdateTime(updateTime);
        return skuMapper.updateSku(sku);
    }

    @Override
    @Transactional
    public int deleteSkuByCode(String skuCode) {
       return skuMapper.deleteSkuByCode(skuCode);
    }

    @Override
    public int insertSku(SkuVo skuVo) {
        if(skuVo.getSkuCode().isEmpty()){
            throw new IllegalArgumentException("库存编号不能为空！");
        }
        if(isExisted(skuVo.getSkuCode())){
            throw  new IllegalArgumentException("库存编号已存在！");
        }
        //判断是否存在该库存信息
        if( !(skuColorSizeMapper.checkUnique(skuVo.getSkuCode()) > 0)){
            throw new IllegalArgumentException("不存在该库存信息，无法设置库存！");
        }
        LoginUser loginUser=tokenService.getLoginUser(ServletUtils.getRequest());
        String createBy=loginUser.getUsername();
        Date createTime = new Date();
        Sku sku = new Sku(skuVo);
        sku.setCreateBy(createBy);
        sku.setCreateTime(createTime);
        return skuMapper.insertSku(sku);
    }

    @Override
    public List<SkuVo> findAllStockEmpty() {
        return skuMapper.findAllStockEmpty();
    }

    /**
     * 查看编号是否存在
     * @param skuCode
     * @return true 存在
     */
    @Override
    public boolean isExisted(String skuCode) {
        return skuMapper.isExisted(skuCode) > 0;
    }

    @Override
    public String generateSkuCode(String productSn) {
        String skuCode = "kc"+ productSn;
        if(isExisted(skuCode)){
            skuCode=generateUUID();
        }
        return skuCode;
    }

    /**
     * 判断库存雨量能否补发
     * @param skuMap
     * @return
     */
    @Override
    public boolean isStockSufficient(Map<String, Integer> skuMap) {
       boolean flag = true;
        for (String s : skuMap.keySet()) {
            int stock = skuMapper.findSkuByCode(s).getStock();
            if(stock < skuMap.get(s)){
                flag = false;
            }
        }
        return flag;
    }

    @Override
    @Transactional
    public int batchUpdateStock(Map<String, Integer> skuMap) {
        int res=skuMapper.batchUpdateStock(skuMap);
        if(res != skuMap.size()){
            log.info("批量出库失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BusinessProcessException("出库失败");
        }
        skuRecordService.insertRecord(skuMap,SkuRecordType.OUT.getSignal());
        return res;
    }

    @Override
    public int batchAddStock(Map<String, Integer> skuMap) {
        int res = skuMapper.batchAddStock(skuMap);
        if(res != skuMap.size()){
            log.info("批量入库失败！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BusinessProcessException();
        }
        skuRecordService.insertRecord(skuMap, SkuRecordType.IN.getSignal());
        return res;
    }

    String generateUUID(){
        String id = "kc"+UUID.randomUUID().toString().replace("-","").substring(0,3);
        if(isExisted(id)){
            generateUUID();
        }
        return id;
    }
}
